# coding=utf8

# Create your views here.
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from forms import *
from models import *
from utils import import_stu_from_file, import_stu_from_text 
from choices import *
from active_show_funcs import active_show_func
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.utils import simplejson
from datetime import datetime

def home(request):
    # return render_to_response("content/index.html")
    return HttpResponseRedirect(reverse('course_list'))

def course_list(request):
    if request.is_ajax():
        form = DataTableForm(request.GET)
        if form.is_valid():   
            courses = Course.objects.all()
            iDisplayLength = int(form.cleaned_data['iDisplayLength'])
            paginator = Paginator(courses, iDisplayLength)
            iDisplayStart = int(form.cleaned_data['iDisplayStart'])
            page = iDisplayStart / iDisplayLength + 1
            try:
                courses = paginator.page(page)
            except (EmptyPage, InvalidPage):
                courses = paginator.page(paginator.num_pages)
            data = {
                    "courses":courses,
                    "sEcho":form.cleaned_data['sEcho']              
                }
            return render_to_response("content/course_list.json", data, context_instance=RequestContext(request), mimetype='application/json')     
        
    return render_to_response("content/course_list.html", context_instance=RequestContext(request))

def lesson_list(request):
    lessons = Lesson.objects.all()
    return render_to_response("content/lesson_list.html", {'lessons':lessons}, context_instance=RequestContext(request))

def class_list(request):
    clses = Class.objects.all()
    return render_to_response("content/class_list.html", {'clses':clses}, context_instance=RequestContext(request))

def course_detail(request, cid):
    course = get_object_or_404(Course, pk=cid)        
    return render_to_response("content/course_detail.html", {'course':course}, context_instance=RequestContext(request))

def lesson_detail(request, lid):
    lesson = get_object_or_404(Lesson, pk=lid)
    active_types = ActiveType.objects.all()       
    return render_to_response("content/lesson_detail.html", {'lesson':lesson, 'active_types':active_types}, context_instance=RequestContext(request))

def class_detail(request, cid):
    cls = get_object_or_404(Class, pk=cid)        
    return render_to_response("content/class_detail.html", {'cls':cls}, context_instance=RequestContext(request))

def class_add(request):
    stus = User.objects.all()
    if request.method == 'POST':
        form = ClassForm(request.POST)
        if form.is_valid():
            code = form.cleaned_data['code']
            name = form.cleaned_data['name']
            desc_str = form.cleaned_data['desc']
            cls = Class(code='code', name=name)
            cls.save()
            if desc_str:
                desc = Attach(label=u"班级简介", content=desc_str)
                desc.save()
                cls.attachs.add(desc)
                cls.save()

            return HttpResponseRedirect(reverse('class_detail', kwargs={'cid':cls.id}))
        else:
            data = {
                'stus':stus,
                'form':form,
            }
            return render_to_response("content/class_add.html", data, context_instance=RequestContext(request))
    else:
        form = CourseForm()
        data = {
            'stus':stus,
            'form':form,
        }
        return render_to_response("content/class_add.html", data, context_instance=RequestContext(request))

def course_add(request):
    if request.method == 'POST':
        form = CourseForm(request.POST)
        if form.is_valid():
            code = form.cleaned_data['code']
            name = form.cleaned_data['name']
            syllabus = form.cleaned_data['syllabus']
            experiment = form.cleaned_data['experiment']
            course = Course(code=code, name=name)
            course.save()
            if syllabus:
                sy = Attach(label=u"教学大纲", content=syllabus)
                sy.save()
                course.attachs.add(sy)
                course.save()
            if experiment:
                ex = Attach(label=u"实验大纲", content=experiment)
                ex.save()
                course.attachs.add(ex)
                course.save()
            return HttpResponseRedirect(reverse('course_detail', kwargs={'cid':course.id}))
        else:
            return render_to_response("content/course_add.html", {'form':form}, context_instance=RequestContext(request))
    else:
        form = CourseForm()
        return render_to_response("content/course_add.html", {'form':form}, context_instance=RequestContext(request))
    
def lesson_add(request):
    courses = Course.objects.all()
    classes = Class.objects.all()
    
    if request.method == 'POST':
        form = LessonForm(request.POST)
        if form.is_valid():
            course_id = form.cleaned_data['course_id']
            code = form.cleaned_data['code']
            clses = form.cleaned_data['clses']
            desc_str = form.cleaned_data['desc']
            
            course = Course.objects.get(pk=course_id)
            lesson = Lesson(course=course, code=code, teacher=request.user)
            lesson.save()
            
            if desc_str:
                desc = Attach(label=u"班级简介", content=desc_str)
                desc.save()
                lesson.attachs.add(desc)
                lesson.save()
            
            for cls_id in clses:
                cls = Class.objects.get(pk=cls_id)
                lesson.clses.add(cls)
            lesson.save()
            return HttpResponseRedirect(reverse('lesson_detail', kwargs={'lid':lesson.id}))
        else:
            data = {
                'courses':courses,
                'classes':classes,
                'form':form,
            }
            return render_to_response("content/lesson_add.html", data, context_instance=RequestContext(request))
    else:
        form = LessonForm()
        data = {
            'courses':courses,
            'classes':classes,
            'form':form,
        }
        return render_to_response("content/lesson_add.html", data, context_instance=RequestContext(request))
        
def student_import(request):
    if request.method == 'POST':
        import_type = request.POST['type']
        if import_type == 'file' or import_type == 'text':
            result_list = None
            if import_type == 'file':
                form = StuImportFileForm(request.POST, request.FILES)
                if form.is_valid():
                    stu_file = form.cleaned_data['stu_file']
                    result_list = import_stu_from_file(stu_file)
            else:
                form = StuImportTextForm(request.POST)
                if form.is_valid():
                    stu_text = form.cleaned_data['stu_list']
                    result_list = import_stu_from_text(stu_text)
            return render_to_response("content/student_import_result.html", {'result_list':result_list}, context_instance=RequestContext(request))
        
    return render_to_response("content/student_import.html", context_instance=RequestContext(request))
    
def test_add(request):
    is_success = False
    errors = ""
    if request.is_ajax() and request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            active = form.cleaned_data['active_id']
            atom = form.cleaned_data['atom_id']
            oj = form.cleaned_data['oj_plat']
            contest_id = form.cleaned_data['contest_id']
            
            test = Test(active=active, atom=atom, oj=oj, contest_id=contest_id)
            test.save()
            is_success = True
        else:
            errors += form.errors
    data = {'is_success':is_success, 'errors':errors}
    return HttpResponse(simplejson.dumps(data), mimetype='application/json')
            
        
    
def active_add(request, lid, aid):    
    lesson = get_object_or_404(Lesson, pk=lid)
    active_type = get_object_or_404(ActiveType, pk=aid)
    if request.is_ajax() and request.method == 'POST':
        form = ActiveForm(request.POST)
        is_success = False
        error_msg = ''
        active_id = -1
        if form.is_valid():
            name = form.cleaned_data['name']
            desc_str = form.cleaned_data['desc']
            active = Active(type=active_type, lesson=lesson, name=name, create_time=datetime.now())
            active.save()
            if desc_str:
                desc = Attach(label=u"描述", content=desc_str)
                desc.save()
                active.attachs.add(desc)
                active.save()
            is_success = True
            active_id = active.id
        else:
            error_msg = form.errors
        data = {'is_success':is_success, 'errors': error_msg, 'active_id':active_id}
        return HttpResponse(simplejson.dumps(data), mimetype='application/json')
    
    data = {
        'lesson':lesson,
        'active_type':active_type,
        'atom_templates':atom_templates,
        'oj_choices':oj_choices,
    }
    return render_to_response("content/active_add.html", data, context_instance=RequestContext(request))

def active_detail(request, aid):
    active = get_object_or_404(Active, pk=aid)
    active_show = active_show_func[active.type]
    return active_show(request, active)

def active_type_list(request):
    active_types = ActiveType.objects.all()
    return render_to_response("content/active_type_list.html", {'active_types':active_types}, context_instance=RequestContext(request))


def active_type_add(request):
    form = ActiveTypeForm()
    if request.method == "POST":
        form = ActiveTypeForm(request.POST)
        if form.is_valid():
            new_type = ActiveType(label=form.cleaned_data['label'])
            new_type.save()
            desc_str = form.cleaned_data['desc']
            if desc_str:
                desc = Attach(label=u"描述", content=desc_str)
                desc.save()
                new_type.attachs.add(desc)
                new_type.save()
            return HttpResponseRedirect(reverse('active_type_detail', kwargs={'aid':new_type.id}))
    return render_to_response("content/active_type_add.html", {'form':form}, context_instance=RequestContext(request))

def active_type_detail(request, aid):
    active_type = get_object_or_404(ActiveType, pk=aid)
    return render_to_response("content/active_type_detail.html", {'active_type':active_type, 'atom_choices':atom_choices}, context_instance=RequestContext(request))

def active_type_atom_add(request):
    if request.method == "POST":
        form = AtomForm(request.POST)
        if form.is_valid():
            active_type=form.cleaned_data['active_type']
            label = form.cleaned_data['label']
            atom = int(form.cleaned_data['atom'])
            if not label:
                label = atom_label_list[atom]
            a = ActiveTypeAtom(active_type=active_type, label=label, atom=atom)
            a.save()
            return HttpResponseRedirect(reverse('active_type_detail', kwargs={'aid':active_type.id}))
    return HttpResponse("404")
   